from flask import Flask, jsonify, request
from flask_cors import CORS
from waitress import serve
import logging
from functools import wraps

# 初始化 Flask 应用
app = Flask(__name__)

# 配置 CORS，允许所有域名访问所有路由
CORS(app, resources={r"/*": {"origins": "*"}})

# 配置日志记录
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s",
    handlers=[logging.FileHandler("app.log"), logging.StreamHandler()],
)
logger = logging.getLogger(__name__)


# 创建统一的响应格式函数
def create_response(data=None, message="Success", status_code=200):
    """
    生成标准的 JSON 响应。

    :param data: 要返回的数据，默认为 None
    :param message: 响应消息，默认为 "Success"
    :param status_code: HTTP 状态码，默认为 200
    :return: tuple (JSON 响应, 状态码)
    """
    response = {"success": status_code < 400, "message": message, "data": data}
    return jsonify(response), status_code


# 错误处理装饰器
def handle_errors(func):
    """
    装饰器，用于捕获视图函数中的异常并返回统一的错误响应。

    :param func: 被装饰的视图函数
    :return: 包装后的视图函数
    """

    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            logger.exception("An error occurred while processing the request.")
            return create_response(message=str(e), status_code=500)

    return wrapper


# 定义 GET /api/data 路由
@app.route("/api/data", methods=["GET"])
@handle_errors
def get_data():
    """
    处理 GET 请求，返回一个简单的 JSON 消息。

    :return: tuple (JSON 响应, 状态码)
    """
    data = {"message": "Hello from Flask with CORS enabled!", "status": "success"}
    return create_response(data=data)


# 定义 GET /api/menus 路由
@app.route("/api/menus", methods=["GET"])
@handle_errors
def get_menus():
    """
    处理 GET 请求，返回菜单项的 JSON 数据。

    :return: tuple (JSON 响应, 状态码)
    """
    menu_items = [
        {"index": "0", "icon": "house", "label": "首页"},
        {
            "index": "1",
            "icon": "document",
            "label": "学生人数统计表",
            "children": [
                {"index": "1-1", "icon": "pie-chart", "label": "高职"},
                {"index": "1-2", "icon": "connection", "label": "中职"},
            ],
        },
        {"index": "2", "icon": "files", "label": "专业设置汇总表"},
        {"index": "3", "icon": "collection", "label": "获奖情况统计表"},
        {
            "index": "4",
            "icon": "reading",
            "label": "业务办理流程",
            "children": [
                {"index": "4-1", "icon": "list", "label": "补办毕业证明书"},
                {"index": "4-2", "icon": "checked", "label": "在校生休学"},
            ],
        },
    ]
    return create_response(data=menu_items)


# 定义 POST /api/data 路由
@app.route("/api/data", methods=["POST"])
@handle_errors
def post_data():
    """
    处理 POST 请求，接收 JSON 数据并返回接收到的数据。

    :return: tuple (JSON 响应, 状态码)
    """
    received_data = request.get_json()
    if not received_data:
        return create_response(message="No JSON data provided.", status_code=400)

    response = {
        "received": received_data,
        "message": "Data received successfully",
        "status": "success",
    }
    return create_response(data=response), 201


# 启动服务器
if __name__ == "__main__":
    serve(app, host="0.0.0.0", port=8080)
